import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    // if (whiteList.includes(to.path)) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 路由守卫，点击登录按钮就获取到权限菜单,位后来权限设置做铺垫
      // 判断是否存在用户信息，避免重复发送请求
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log(res)
        const otherRoutes = await store.dispatch(
          'permission/filterRoutes',
          res.roles.menus
        )
        // 通过addRoutes添加所有动态路由
        // 固定写法 配合 next({...to,replace:true})使用
        // ...to 表示所有访问路由的信息
        // replace:true 表示重新进一次首页
        // 最后需要return终止下面next()放行
        console.log(otherRoutes)
        router.addRoutes([
          ...otherRoutes,
          { path: '*', redirect: '/404', hidden: true }
        ])
        next({
          ...to,
          replace: true
        })
        return
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach((to, from) => {
  document.title = '人资管理项目--' + to?.meta?.title || '人资管理项目'
  NProgress.done()
})
